import json
from datetime import datetime, timezone
import threading

class LLMLogger:
    def __init__(self, log_file="llm_io_log.jsonl"):
        self.log_file = log_file
        self.lock = threading.Lock()

    def log(self, request, response):
        """记录HTTP请求和响应"""
        try:
            def parse_body(body_str):
                try:
                    return json.loads(body_str)
                except json.JSONDecodeError:
                    return body_str

            # 读取并保存body内容
            req_body = request.read().decode('utf-8')
            resp_body = response.read().decode('utf-8')

            # 构建日志条目
            log_entry = {
                "timestamp": datetime.now(timezone.utc).isoformat(),
                "request": {
                    "url": str(request.url),
                    "method": request.method,
                    "headers": dict(request.headers),
                    "body": parse_body(req_body)
                },
                "response": {
                    "status_code": response.status_code,
                    "headers": dict(response.headers),
                    "body": parse_body(resp_body)
                }
            }

            # 写入文件（线程安全）
            with self.lock, open(self.log_file, "a", encoding="utf-8") as f:
                f.write(json.dumps(log_entry, ensure_ascii=False) + "\n")

        except Exception as e:
            # 避免日志记录失败影响主流程
            print(f"LLM日志记录失败: {str(e)}")
